import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../lib_basemodel/country/country_model.dart';
import '../../lib_network/http_api.dart';
import '../../lib_network/http_helper.dart';
import '../veri_code/veri_code_page.dart';

class LoginWithPhoneController extends GetxController {
  late TextEditingController textController;
  late FocusNode focusNode;

  /// 问题描述Rx
  final phoneRx = ''.obs;

  bool requesting = false;

  // 响应式变量（必须使用Rx类型）
  final Rx<CountryModel?> _countryModel = Rx<CountryModel?>(null);
  CountryModel? get countryModel => _countryModel.value;
  set countryModel(CountryModel? value) {
    //  _countryModel.value = value
    _countryModel.value = value;
    update(['country_code']);
  }

  /// 按钮的load状态
  final Rx<bool> isLoading = Rx(false);
  final Rx<bool> isHeight = Rx(false);

  /// 输入框内容
  final Rx<String> inputText = Rx('');

  @override
  void onInit() {
    super.onInit();

    focusNode = FocusNode();
    textController = TextEditingController();

    // ThirdLoginPlatformFactory.ins.addLoginPlatform(PhoneLoginPlatform());
    // ThirdLoginPlatformFactory.ins.listenLoginEvent.listen((event) {
    //   if (event.suc) {
    //     authSuccessWithThirdPlatform(event.authRsp?.authed,
    //         loginPlatform: event.platform);
    //   } else {
    //     showToast(event.errorMsg ?? T.current!.server_exception);
    //   }
    // });

    fetchAreaCode();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  /// 请求区域区号：

// 获取国家区号（默认取第1个）
  fetchAreaCode() async {
    var response = await HttpHelper.instance().post(
      HttpApi.getcountry,
      showLoading: true,
      showToast: true,
    );
    if (response.isSuccess) {
      List tmpDataList = response.result['items'];
      List dataList = [];
      for (var element in tmpDataList) {
        CountryModel country = CountryModel.fromJson(element);
        dataList.add(country);
      }

      countryModel = dataList[0];
      update(['country_code']);
      // UserModelEntity userEntity = UserModelEntity.fromJson(response.result);
      // UserCenter.update(userEntity);

      // if (userEntity.gender != null) {
      //   Get.offAllNamed(FHRouteName.tab);
      // } else {
      //   Get.offAllNamed(FHRouteName.guide_sex);
      // }

      // FHAnalyticsReporter.track(FHTrackEvent.log_withvisitor_success, null);
    }
  }

  /// 调用获取验证码接口
  fetchVerify() async {
    String? areaCode = countryModel?.code;
    // if (areaCode == null || textController.text.trim().isEmpty) return;

    isLoading.value = true;
    update(['login_sms_get_veri']);

    var response = await HttpHelper.instance().post(
      HttpApi.smsVerify,
      body: {"mobile": textController.text.trim(), "areaCode": areaCode},
      showLoading: false,
      showToast: true,
    );
    if (response.isSuccess) {
      Get.to(() => VeriCodePage(
          phoneNum: textController.text.trim(), areaCode: areaCode!));
    }

    // Future.delayed(const Duration(seconds: 10), () {
    isLoading.value = false;
    update(['login_sms_get_veri']);
    // });
  }

  updataLoginSmsGetVeri(String inputStr) {
    if (inputStr.trim().isNotEmpty) {
      isHeight.value = true;
    } else {
      isHeight.value = false;
    }

    update(['login_sms_get_veri']);
  }

  jumpSelectCountryPage() {
    // Navigator.of().push(CupertinoPageRoute(builder: (context) {
    //   return SelectCountryPage(
    //     onCountrySelected: (CountryModel? selectedCountry) {
    //       if (selectedCountry != null) {
    //         // 处理选中的国家模型
    //         print('Selected country: ${selectedCountry.country}');

    //         _ctrl.countryModel = selectedCountry;
    //       }
    //     },
    //   );
    // }));
  }
}
